﻿using System;
using System.Text.RegularExpressions;

namespace WD.Framework.Utility
{
    public class HandleRegex
    {

        #region 【正则关键字匹配】

        /// <summary>
        /// 【公开】匹配关键字【内容、正则表达式、排除之前文本、排除之后文本、是否单行】
        /// </summary>
        public MatchCollection Solo_GetMathStr(string Input, string RegexStr, string StrB, string StrE, bool Singleline)
        {
            return _GetMathStr(Input, RegexStr, StrB, StrE, Singleline);
        }
        /// <summary>
        /// 【公开】匹配关键字【内容、匹配前、匹配后、是否单行】
        /// </summary>
        public MatchCollection Solo_GetMathStr(string Input, string StrB, string StrE, bool Singleline)
        {
            return _GetMathStr(Input, "", StrB, StrE, Singleline);
        }
        /// <summary>
        /// 【公开】匹配关键字【内容、正则表达式、排除之前文本、排除之后文本、是否单行】
        /// </summary>
        public string Solo_GetFirstMathStr(string Input, string RegexStr, string StrB, string StrE, bool Singleline)
        {
            MatchCollection mc = _GetMathStr(Input, RegexStr, StrB, StrE, Singleline);
            return mc.Count == 0 ? "" : mc[0].Value;
        }
        /// <summary>
        /// 【公开】匹配关键字【内容、匹配前、匹配后、是否单行】
        /// </summary>
        public string Solo_GetFirstMathStr(string Input, string StrB, string StrE, bool Singleline)
        {
            MatchCollection mc = _GetMathStr(Input, "", StrB, StrE, Singleline);
            return mc.Count == 0 ? "" : mc[0].Value;
        }

        /// <summary>
        /// 【私有】匹配文本关键字
        /// </summary>
        private MatchCollection _GetMathStr(string Input, string RegexStr, string StrB, string StrE, bool Singleline)
        {
            MatchCollection mc = null;
            if ((StrB != "" || StrE != ""))
            {
                if (RegexStr != "")
                {
                    try
                    {
                        int indexB = Input.IndexOf(StrB);
                        int indexE = Input.IndexOf(StrE);
                        Input = Input.Substring(indexB, indexE - indexB);
                    }
                    catch (Exception)
                    {
                    }
                }
                else
                {
                    RegexStr = string.Format("(?<={0}).*?(?={1})", StrB, StrE);
                }
            }
            Regex rg;
            if (Singleline)
            {
                rg = new Regex(RegexStr, RegexOptions.Singleline);
            }
            else
            {
                rg = new Regex(RegexStr);
            }
            mc = rg.Matches(Input);
            return mc;
        }

        #endregion
    }
}